package com.tanyoujie.cart.controller;

import com.tanyoujie.cart.service.CartService;
import com.tanyoujie.cart.vo.CartItemVo;
import com.tanyoujie.cart.vo.CartVo;
import com.tyj.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@Slf4j
public class CartController {

    @Autowired
    CartService cartService;

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("count") Integer count,
                            RedirectAttributes ra){
        CartItemVo cartItemVo= cartService.addToCart(skuId,count);
        ra.addAttribute("skuId",cartItemVo.getSkuId());//使用RedirectAttributes封装的数据会在重定向后自动拼接到重定向路径参数
        return "redirect:http://cart.gulimall.com/successPage.html";
    }

    @GetMapping("/successPage.html")
    public String resultSuccessPage(@RequestParam("skuId") Long skuId,Model model){
        CartItemVo cartItemVo= cartService.getCartItem(skuId);
        model.addAttribute("skuInfo",cartItemVo);
        return "success";
    }

    @GetMapping("/cart.html")
    public String getCart(Model model){
        CartVo cartVo = cartService.getCart();
        log.debug("返回购物车的数据="+cartVo);
        model.addAttribute("cartInfo",cartVo);
        return "cart";
    }

    @PostMapping("/editCartCount")
    @ResponseBody
    public R editCartCount(Long skuId, Integer count){
        R r = cartService.editCartCount(skuId,count);
        return r;
    }

    @PostMapping("/deleteCart")
    @ResponseBody
    public R deleteCart(Long skuId){
        cartService.deleteCart(skuId);
        return R.ok();
    }

    @GetMapping("/getCartNum")
    @ResponseBody
    public R getCartNum(){
        Long cartNum=cartService.getCartNum();
        Map map=new HashMap();
        map.put("cartNum",cartNum);
        return R.ok().setData(map);
    }

    @PostMapping("/checkCart")
    @ResponseBody
    public R checkCart(@RequestParam("isChecked") boolean isChecked,@RequestParam("skuId") Integer skuId){
        cartService.checkCart(isChecked,skuId);
        return R.ok();
    }

    @ResponseBody
    @RequestMapping("/getCheckedItems")
    public List<CartItemVo> getCheckedItems() {
        return cartService.getCheckedItems();
    }
}
